package com.dgutnw.yeziyin.sbexp.exp03_covid19_realtimedate.services;

import com.dgutnw.yeziyin.sbexp.exp03_covid19_realtimedate.models.RegionStats;
import lombok.Data;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.tomcat.util.file.ConfigurationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;



import javax.swing.plaf.synth.Region;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
@Data
public class Covid19DateService implements InitializingBean {
    //将url设置为静态且不可更改的常量
    private static final String Covid19_Date_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private final ArrayList<RegionStats>  regionStatsList = new ArrayList<>();
    private Logger Log= LoggerFactory.getLogger(Covid19DateService.class); //日志记录
    private Resource body;

    // 设置每日凌晨1.更新任务,更新
    @Scheduled(cron = "${yzy.Schedules.updateVirusDataCron}")
    public void fetchCovid19Data() throws IOException{

        regionStatsList.removeAll(regionStatsList); //初始化列表

        if(regionStatsList.isEmpty()){
            Log.info("初始化数据列表完成");
        }
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(Covid19_Date_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","yeziyin"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        body = exchange.getBody();

        Reader readin;
        if(body != null){
            Log.info("数据拉取成功");
            readin = new InputStreamReader(body.getInputStream());
            Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(readin);

            for (CSVRecord record : records) {
                RegionStats model = new RegionStats();
                model.setState(record.get("Province/State"));
                model.setCountry(record.get("Country/Region"));
                int latesttotal = Integer.parseInt(record.get(record.size() - 1));
                int thedaybefore = Integer.parseInt(record.get(record.size() - 2));
                model.setLatestTotalCases(latesttotal);
                model.setDiffFromPrevDay(latesttotal - thedaybefore);
                regionStatsList.add(model);
            }
        }
    }

    public List<RegionStats> getRegionStatsList() {
        return regionStatsList;
    }

    //    程序启动时，自动拉取一次数据
    @Override
    public void afterPropertiesSet() throws Exception{
        fetchCovid19Data();
    }



}
